package netty.demo.nio.selector.acceptAndRead;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

import static netty.demo.nio.byteBuffer.ByteBufferUtil.debugRead;

/**
 * @author Zed
 * @description Selector--处理Accept事件
 * @date 2022/10/23 10:13
 */
@Slf4j
public class Server {
    @SneakyThrows
    public static void main(String[] args) {
        //1.创建selector 管理多个channel
        Selector selector = Selector.open();
        ServerSocketChannel ssc = ServerSocketChannel.open();
        ssc.configureBlocking(false);
        //2.建立selector和channel的联系(注册)
        //sscKey就是将来事件发生后,通过它可以知道事件和哪个channel的事件
        SelectionKey sscKey = ssc.register(selector, 0, null);
        //sscKey只关注accept事件
        sscKey.interestOps(SelectionKey.OP_ACCEPT);
        System.out.println("sscKey:" + sscKey);
        ssc.bind(new InetSocketAddress(8080));
        while (true) {
            //3.select方法,没有事件发生，线程阻塞；有事件发生，线程才会恢复运行
            //select在事件未处理时 不会阻塞，事件发生后要么取消，要么处理，不能置之不理
            selector.select();
            //4.处理事件 selectionKeys内部包含了所有发生的事件
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            Iterator<SelectionKey> iterator = selectionKeys.iterator();
            while (iterator.hasNext()) {
                SelectionKey key = iterator.next();
                iterator.remove();
                System.out.println("key:" + key);
                //5.区分事件类型
                if (key.isAcceptable()) {  //如果是Accept
                    ServerSocketChannel channel = (ServerSocketChannel) key.channel();
                    SocketChannel sc = channel.accept();
                    sc.configureBlocking(false);
                    SelectionKey scKey = sc.register(selector, 0, null);
                    scKey.interestOps(SelectionKey.OP_READ);
                    System.out.println(sc);
                    System.out.println("scKey:" + scKey);
                } else if (key.isReadable()) {  //如果是Read,拿触发事件的channel
                    try {
                        SocketChannel channel = (SocketChannel) key.channel();
                        ByteBuffer buffer = ByteBuffer.allocate(4);
                        int readCount = channel.read(buffer);//如果是正常断开,read方法的返回值是-1
                        if (readCount == -1) {
                            key.cancel();
                        } else {
                            buffer.flip();
                            debugRead(buffer);
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                        key.cancel();
                    }
                }
            }
        }
    }
}
